package utils

import (
	"sort"
	"strconv"
)

// A data structure to hold a key/value pair.
type Pair struct {
	Key   string
	Value int
}

// A slice of Pairs that implements sort.Interface to sort by Value.
type PairList []Pair

func (p PairList) Swap(i, j int)      { p[i], p[j] = p[j], p[i] }
func (p PairList) Len() int           { return len(p) }
func (p PairList) Less(i, j int) bool { return p[i].Value < p[j].Value }
func (p PairList) Keys() []string {
	var keys []string
	//range遍历数组
	for _, value := range p {
		keys = append(keys, value.Key)
	}
	return keys
}

// A function to turn a map into a PairList, then sort and return it.
func SortMapByValue(m map[string]string) PairList {
	p := make(PairList, len(m))
	i := 0
	for k, v := range m {
		intV, err := strconv.Atoi(v)
		if err == nil {
			p[i] = Pair{k, intV}
		}
	}
	sort.Sort(p)
	return p
}
